#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <arpa/inet.h>
#include <sys/socket.h>
#include <sys/select.h>

// ============== 备注 ==============
// 已经完成了回复消息的功能！
// 不过需要根据0.(STM32, 已完成)，1.(手机读文件，未完成)，2.(手机删除文件，未完成)分别调用不同的函数
// 加油！
// ============== 宏定义 ==============
#define PORT            9080
#define BUF_SIZE        4096
#define MAX_CLIENTS     10

// ============== 宏函数 ==============
#define CHECK_ERROR(cond, msg, cleanup) \
    if(cond) { perror(msg); cleanup; return -1; }

// ============== 函数声明 ==============
void send_http_response(int fd, const char* content_type, const char *content);

// ============== 主函数 ==============
int main() {
    // 检查句柄返回
    int ret_check = 0;

    // 创建socket
    int socket_fd = socket(AF_INET, SOCK_STREAM, 0);
    CHECK_ERROR(socket_fd < 0, "socket", NULL);

    // 设置端口复用
    int reuse = 1;
    ret_check = setsockopt(socket_fd, SOL_SOCKET, SO_REUSEADDR, &reuse, sizeof(reuse));
    CHECK_ERROR(ret_check < 0, "setsockopt", close(socket_fd));

    // 绑定地址
    struct sockaddr_in addr = {
        .sin_family = AF_INET,
        .sin_port = htons(PORT),
        .sin_addr.s_addr = INADDR_ANY
    };

    ret_check = bind(socket_fd, (struct sockaddr*)&addr, sizeof(addr));
    CHECK_ERROR(ret_check < 0, "bind", close(socket_fd));

    // 开始监听
    ret_check = listen(socket_fd, MAX_CLIENTS);  // [!] 使用宏定义
    CHECK_ERROR(ret_check < 0, "listen", close(socket_fd));

    printf("Server started on port %d\n", PORT);

    // 创建监听队列
    int client_fds[MAX_CLIENTS] = {0};
    int n_clients = 0;

    // base_set，保存下一次循环要监听的文件描述符集合
    fd_set base_set;
    FD_ZERO(&base_set);
    FD_SET(socket_fd, &base_set);
    FD_SET(STDIN_FILENO, &base_set);

    while (1) {
        // 1. 准备工作：更新下标 | 监听
        fd_set read_set;
        FD_ZERO(&read_set);
        memcpy(&read_set, &base_set, sizeof(base_set));

        int max_fd = socket_fd;
        for(int i = 0; i < n_clients; i++){
            if(client_fds[i] > max_fd)
                max_fd = client_fds[i];
        }

        ret_check = select(100, &read_set, NULL, NULL, NULL);
        CHECK_ERROR(ret_check < 0, "select", NULL);

        // 2. 处理新链接, accept并添加到client_fds
        if(FD_ISSET(socket_fd, &read_set)){
            // 接受客户端连接
            struct sockaddr_in client_addr;
            socklen_t addr_len = sizeof(client_addr);

            // 新链接
            int new_fd = accept(socket_fd, (struct sockaddr*)&client_addr, &addr_len);

            // 新链接处理
            if(new_fd < 0){
                perror("accept");
            }
            else if(n_clients < MAX_CLIENTS){
                printf("New client from %s:%d (fd=%d)\n", 
                       inet_ntoa(client_addr.sin_addr), ntohs(client_addr.sin_port), new_fd);
                client_fds[n_clients++] = new_fd;
                FD_SET(new_fd, &base_set);
            }
            else{
                close(new_fd);
                printf("Max clients reached!\n");
            }
        }

        // 3. 处理stdin输入（服务端主动发消息)，广播
        if (FD_ISSET(STDIN_FILENO, &read_set)) {
            printf("Server input > ");
            fflush(stdout);

            char buf[BUF_SIZE];
            if (fgets(buf, sizeof(buf), stdin) == NULL) break;

            // 广播给所有客户端
            for(int i = 0; i < n_clients; i++){
                send_http_response(client_fds[i], "text/plain", buf);
            }
        }

        // 4. 处理客户端消息
        for(int i = 0; i < n_clients; i++){
            int client_fd = client_fds[i];

            if (FD_ISSET(client_fd, &read_set)) {
                char buf[BUF_SIZE];
                ssize_t len = recv(client_fds[i], buf, sizeof(buf) - 1, 0); // 保留空间给'\0'

                // 用户已断开链接
                if (len <= 0) {
                    printf("Client %d disconnected\n", client_fds[i]);
                    
                    FD_CLR(client_fd, &base_set);   
                    close(client_fds[i]);
                    for(int k = i; k < n_clients; k++){
                        client_fds[k] = client_fds[k + 1];
                    }

                    n_clients--;
                    i--;
                }
                else{
                    buf[len] = '\0';
                    printf("From client[fd=%d]:\n%.*s\n", client_fds[i], (int)len, buf);

                    for (int j = 0; j < n_clients; j++) {
                        if (j != i && client_fds[j] > 0) {  // 排除自己和无效连接

                            printf("143:--%s--\n", buf);
                            if (send(client_fds[j], buf, len, 0) < 0) {
                                perror("send");
                                // 可选：标记为断开，下次循环清理
                                close(client_fds[j]);
                                client_fds[j] = 0;
                            }
                        }
                    }
                }
            }
        }
    }

    // 清理
    for(int i = 0; i < n_clients; i++){
        if(client_fds[i] > 0){
            close(client_fds[i]);
        }
    }
    close(socket_fd);
    return 0;
}

// ============== 函数实现 ==============
void send_http_response(int fd, const char *content_type, const char *content) {
    char response[BUF_SIZE];
    int header_len = snprintf(response, sizeof(response),
                              "HTTP/1.1 200 OK\r\n"
                              "Content-Type: %s\r\n"
                              "Content-Length: %zu\r\n\r\n",
                              content_type, strlen(content));
    if(header_len < 0 || header_len + strlen(content) >= sizeof(response)){
        return;
    }
    strcat(response, content);

    send(fd, response, strlen(response), 0);
}

